# -*- coding: utf-8 -*-
from db.mysql import MysqlClient
import requests, json
import aiohttp, asyncio
from itertools import product
from common.helper import Helper
from common.config import *
from urllib.parse import urlencode


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "境外全球游保险"

    # 生成数据
    def genProductInfo(self):
        plan = {
            "planA": {
                "year": ["0-17"],
                "days": ["1d", "5d", "9d", "13d", "16d", "22d", "30d", "365d"],
                "accident_death": ["100000"],
                "common_traffic": [""],
                "accident_medical": ["200000"],
                "serious_medical": ["500000"],
                # 遗体返送
                "death_back": ["500000"],
                # 骨灰盒费用
                "casket_fee": ["8000"],
                # 安葬费用
                "burial_fee": ["16000"],
                # 未成年子女返送回国
                "child_return": [""],
                # 亲属探访费用
                "relate_mourn": [""],
                # 后事处理费用
                "care_affairs": [""],
                # 紧急搜救
                "nervous_help": ["40000"],

            },
            "planB": {
                "year": ["18-80"],
                "days": ["1d", "5d", "9d", "13d", "16d", "22d", "30d", "365d"],
                "accident_death": ["200000"],
                "common_traffic": ["200000"],
                "accident_medical": ["200000"],
                "serious_medical": ["500000"],
                # 遗体返送
                "death_back": ["500000"],
                # 骨灰盒费用
                "casket_fee": ["8000"],
                # 安葬费用
                "burial_fee": ["16000"],
                # 未成年子女返送回国
                "child_return": [""],
                # 亲属探访费用
                "relate_mourn": [""],
                # 后事处理费用
                "care_affairs": [""],
                # 紧急搜救
                "nervous_help": ["40000"],

            },
            "planC": {
                "year": ["18-80"],
                "days": ["1d", "5d", "9d", "13d", "16d", "22d", "30d", "365d"],
                "accident_death": ["500000"],
                "common_traffic": ["500000"],
                "accident_medical": ["500000"],
                "serious_medical": ["1000000"],
                # 遗体返送
                "death_back": ["1000000"],
                # 骨灰盒费用
                "casket_fee": ["8000"],
                # 安葬费用
                "burial_fee": ["16000"],
                # 未成年子女返送回国
                "child_return": ["12000"],
                # 亲属探访费用
                "relate_mourn": ["12000"],
                # 后事处理费用
                "care_affairs": ["6000"],
                # 紧急搜救
                "nervous_help": ["40000"],

            },
        }

        for k in plan:
            for v in product(plan[k]["year"], plan[k]["days"], plan[k]["accident_death"], plan[k]["common_traffic"],
                             plan[k]["accident_medical"], plan[k]["serious_medical"], plan[k]["death_back"],
                             plan[k]["casket_fee"], plan[k]["burial_fee"], plan[k]["child_return"],
                             plan[k]["relate_mourn"], plan[k]["care_affairs"], plan[k]["nervous_help"]):
                data = Helper.formatProductInfo(plan[k], v)

                yield data

    async def requestJson(self, dt):
        payload = self.filterPayload(dt)
        async with aiohttp.ClientSession() as session:
            async with session.post(url=domain[self.name]["url"], headers=domain[self.name]["header"],
                                    data=payload,ssl=False) as resp:
                res = await resp.text()

                if "result" in res:
                    price = Helper.decimalParse( json.loads( res )["result"] )
                    data = {
                        "name":self.name,
                        "company":"德华安顾人寿",
                        "price":price,

                    }
                    data.update( dt )
                    Helper.mergeTable( self.name,self.mysql,data )

    def filterPayload(self, data=None):
        params = '''
        productNo: 20
        insuredSex: 
        insuredBirthday: 
        insuranceYears: 365
        paymentPeriod: 
        guaranteeAmount: 
        mult: 0
        payIntv: 0
        insuyearFlag: D
        payendyearFlag: 
        contPlanCode: nets0227
        '''
        payload = Helper.perfectJson(params)
        if data["year"] == "0-17":
            payload["insuranceYears"] = data["days"].replace("d", "")
        else:
            payload["insuranceYears"] = data["days"].replace("d", "")
            if data["accident_death"] == "200000":
                payload["contPlanCode"] = "nets0225"
            else:
                payload["contPlanCode"] = "nets0226"
        return urlencode(payload).replace("+","")

    def asyncTask(self):

        tasks = [self.requestJson(data) for data in self.genProductInfo()]
        event_loop = asyncio.get_event_loop()
        event_loop.run_until_complete(asyncio.gather(*tasks))
        event_loop.close()
    def test(self):
        data = {'productNo': ' 20', 'insuredSex': '', 'insuredBirthday': '', 'insuranceYears': '365', 'paymentPeriod': '', 'guaranteeAmount': '', 'mult': ' 0', 'payIntv': ' 0', 'insuyearFlag': ' D', 'payendyearFlag': '', 'contPlanCode': 'nets0226'}
        payload = urlencode(data).replace("+","")
        header = headers_raw_to_dict(
            b'''
            Accept: application/json, text/javascript, */*; q=0.01
            Accept-Encoding: gzip, deflate, br
            Accept-Language: zh-CN,zh;q=0.9
            Connection: keep-alive
            Content-Length: 162
            Content-Type: application/x-www-form-urlencoded; charset=UTF-8
            Cookie: _ga=GA1.2.1753139979.1576025815; JSESSIONID=7356CC7903DD5528B89C33C0E125DDE9; _gid=GA1.2.2043856774.1588226583
            Host: www.ergo-life.cn
            Origin: https://www.ergo-life.cn
            Referer: https://www.ergo-life.cn/ly_product/20/26/quanqiuyou.html
            Sec-Fetch-Dest: empty
            Sec-Fetch-Mode: cors
            Sec-Fetch-Site: same-origin
            User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.113 Safari/537.36
            X-Requested-With: XMLHttpRequest
            '''
        )
        print( payload )
        r =requests.post( url = domain[self.name]["url"],headers=header,data=payload,verify=False)
        print( r.text )
